/*******************************************************************************
 * The MOSES project, model based software engineering of networked embedded systems.
 * 
 * Copyright (C) 2010-2013, University of Applied Sciences Wildau,
 * Telematics Research Group, http://www.tm.th-wildau.de/research-group
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses>.
 * 
 * Contributors:
 *     University of Applied Sciences Wildau - initial API and implementation
 * 
 * If you are interested in a commercial license please contact us via 
 * e-mail: ralf.vandenhouten@th-wildau.de.
 ******************************************************************************/
package de.thwildau.tm.moses.asn1.util;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;

import com.google.inject.Singleton;

import de.thwildau.tm.moses.asn1.asn1.Asn1;
import de.thwildau.tm.moses.asn1.asn1.Assignment;
import de.thwildau.tm.moses.asn1.asn1.Constraint;
import de.thwildau.tm.moses.asn1.asn1.ElementSetSpec;
import de.thwildau.tm.moses.asn1.asn1.ElementSetSpecs;
import de.thwildau.tm.moses.asn1.asn1.Elements;
import de.thwildau.tm.moses.asn1.asn1.IntegerValue;
import de.thwildau.tm.moses.asn1.asn1.IntersectionElements;
import de.thwildau.tm.moses.asn1.asn1.Intersections;
import de.thwildau.tm.moses.asn1.asn1.LowerEndValue;
import de.thwildau.tm.moses.asn1.asn1.LowerEndpoint;
import de.thwildau.tm.moses.asn1.asn1.ModuleDefinition;
import de.thwildau.tm.moses.asn1.asn1.NamedType;
import de.thwildau.tm.moses.asn1.asn1.SingleValue;
import de.thwildau.tm.moses.asn1.asn1.SizeConstraint;
import de.thwildau.tm.moses.asn1.asn1.Type;
import de.thwildau.tm.moses.asn1.asn1.TypeAssignment;
import de.thwildau.tm.moses.asn1.asn1.Unions;
import de.thwildau.tm.moses.asn1.asn1.UpperEndValue;
import de.thwildau.tm.moses.asn1.asn1.UpperEndpoint;
import de.thwildau.tm.moses.asn1.asn1.Value;
import de.thwildau.tm.moses.asn1.asn1.ValueRange;
import de.thwildau.tm.moses.asn1.asn1.ValueRangeValue;
import de.thwildau.tm.moses.asn1.util.generator.GenConstraint;
import de.thwildau.tm.moses.asn1.util.generator.GenSizeConstraint;
import de.thwildau.tm.moses.asn1.util.generator.GenValueRangeConstraint;
 

/**
 * Utility class to find {@link EObject} elements in an ASN.1 file.
 *
 * @author Thomas Kistel
 * @version $Revision: 763 $
 */
@Singleton
public class Asn1ElementFinder {
    
    /**
     * Returns the root element of the ASN.1 file containing the given element.
     * 
     * @param obj the given element.
     * @return the root element of the ASN.1 file containing the given element.
     */
    public Asn1 rootOf(EObject obj) {
        EObject current = obj;
        while (!(current instanceof Asn1))
            current = current.eContainer();
        return (Asn1)current;
    }
    
    /**
     * Returns the Assignment of the given EObject. Returns <code>null</code> if the
     * EObject is outside the scope of an assignment.
     * 
     * @param the given EObject element
     * @return the Assignment or <code>null</code>
     */
    public Assignment assignmentOf(EObject obj) {
        EObject current = obj;
        while (!(current instanceof Assignment))
            current = current.eContainer();
        return (Assignment)current;
    }
    
    /**
     * Returns the ModuleDefinition element of an ASN.1 file of the given element (i.e. in an ASN.1 file the element
     * is always a Child of ModuleDefinition). Returns <code>null</code> if the given element is the root element
     * (ASN) of an ASN.1 file.
     * 
     * @param obj the given element
     * @return the ModuleDefinition element of an ASN.1 file
     */
    public ModuleDefinition getModuleDefinitionOf(EObject obj) {
        EObject current = obj;
        while (!(current instanceof ModuleDefinition)) {
            current = current.eContainer();
            if(current == null)
                return null;
        }   
        return (ModuleDefinition)current;
    }
    
    public List<ElementSetSpec> getConstrainst(EObject obj) {
        Constraint constraint = null;
        if(obj instanceof Constraint) {
            constraint = (Constraint) obj;
        } else if(obj instanceof TypeAssignment) {
            constraint = ((TypeAssignment)obj).getConstraint();
        } else if(obj instanceof NamedType) {
            constraint = ((NamedType)obj).getConstraint();
        } else if(obj instanceof Type) {
            return getConstrainst(obj.eContainer());
        }
        
        if(constraint != null) {
            ElementSetSpecs elementSetSpecs = (ElementSetSpecs) constraint.getConstraintSpec();
            EList<ElementSetSpec> elementSetSpec = elementSetSpecs.getElementSetSpec();
            return elementSetSpec;
        }
        return new ArrayList<ElementSetSpec>(0);
    }
    
    public GenConstraint<Long> getConstraint(List<ElementSetSpec> specs) {
        if(specs != null && specs.size() == 1) {
            ElementSetSpec spec = (ElementSetSpec) specs.get(0);
            if(spec instanceof Unions) {
                EList<Intersections> intersections = ((Unions)spec).getIntersections();
                if(intersections.size() == 1) {
                    Intersections intersection = intersections.get(0);
                    EList<IntersectionElements> intersectionElements = intersection.getIntersectionElements();
                    if(intersectionElements.size() == 1) {
                        IntersectionElements intersectionElement = intersectionElements.get(0);
                        Elements element = intersectionElement.getElements();
                        if(element instanceof SizeConstraint) {
                            Constraint constraint = ((SizeConstraint)element).getConstraint();
                            return getConstraint(getConstrainst(constraint));
                        } else if(element instanceof SingleValue) {
                            Value value = ((SingleValue)element).getValue();
                            if(value instanceof IntegerValue) {
                                long sizeConstraint = ((IntegerValue)value).getValue();
                                return new GenSizeConstraint<Long>(Long.valueOf(sizeConstraint));
                            }
                        } else if(element instanceof ValueRange) {
                            ValueRange range = (ValueRange) element;
                            return new GenValueRangeConstraint<Long>(valueOf(range.getLowerEndpoint()), valueOf(range.getUpperEndpoint()));
                        }
                    }
                }
            }
        }
        return null;
    }
    
    private Long valueOf(LowerEndpoint lowerEndpoint) {
        LowerEndValue value = lowerEndpoint.getValue();
        if(value.getMinValue() != null)
            return Long.valueOf(Integer.MIN_VALUE);
        return valueOf(value.getValue());
    }
    
    private Long valueOf(UpperEndpoint upperEndpoint) {
        UpperEndValue value = upperEndpoint.getValue();
        if(value.getMaxValue() != null)
            return Long.valueOf(Integer.MAX_VALUE);
        return valueOf(value.getValue());
    }
    
    private Long valueOf(ValueRangeValue rangeValue) {
        if(rangeValue instanceof IntegerValue) {
            return ((IntegerValue)rangeValue).getValue();
        }
        throw new UnsupportedOperationException(rangeValue.eClass().getName() + " is currently not supported.");
    }
}
